package com.sup.sale.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sup.sale.mapper.SalesTableMapper;
import com.sup.sale.domain.SalesTable;
import com.sup.sale.service.ISalesTableService;
import com.sup.member.mapper.MemberTableMapper;
import com.sup.member.domain.MemberTable;

@Service
public class SalesTableServiceImpl implements ISalesTableService
{
    @Autowired
    private SalesTableMapper salesTableMapper;

    @Autowired
    private MemberTableMapper memberTableMapper; // 注入会员Mapper

    @Override
    public SalesTable selectSalesTableById(Long id)
    {
        return salesTableMapper.selectSalesTableById(id);
    }

    @Override
    public List<SalesTable> selectSalesTableList(SalesTable salesTable)
    {
        return salesTableMapper.selectSalesTableList(salesTable);
    }

    @Override
    public int insertSalesTable(SalesTable salesTable)
    {
        // 1. 插入销售记录
        int result = salesTableMapper.insertSalesTable(salesTable);

        // 2. 如果销售记录包含会员手机号，则更新会员积分
        if (salesTable.getSalesMember() != null && !salesTable.getSalesMember().isEmpty()) {
            updateMemberPoints(salesTable);
        }

        return result;
    }

    @Override
    public int updateSalesTable(SalesTable salesTable)
    {
        return salesTableMapper.updateSalesTable(salesTable);
    }

    @Override
    public int deleteSalesTableByIds(Long[] ids)
    {
        return salesTableMapper.deleteSalesTableByIds(ids);
    }

    @Override
    public int deleteSalesTableById(Long id)
    {
        return salesTableMapper.deleteSalesTableById(id);
    }

    /**
     * 更新会员积分（增加销售总金额的整数部分）
     */
    private void updateMemberPoints(SalesTable salesTable) {
        // 1. 根据手机号查询会员信息
        MemberTable member = memberTableMapper.selectMemberTableByPhone(salesTable.getSalesMember());

        if (member != null && salesTable.getSalesTotal() != null) {
            // 2. 计算新增积分（取销售总金额的整数部分）
            long pointsToAdd = (long) Math.floor(salesTable.getSalesTotal());

            // 3. 更新会员积分
            member.setMemberPoints(member.getMemberPoints() + pointsToAdd);
            memberTableMapper.updateMemberTable(member);
        }
    }
}